package com.clz.appdesign.appdependence.baseKotlin

import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.clz.appdesign.appdependence.rx.RxBus
import com.clz.appdesign.appdependence.widget.LoadingDialog
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity

import rx.subscriptions.CompositeSubscription

/**
 * @author chenliangzhi
 * @date 2018/1/9
 * @describe Activity的基类
 */

abstract class BaseActivity : RxAppCompatActivity() {
    protected var compositeSubscription: CompositeSubscription? = null
    protected var loadingDialog: LoadingDialog? = null
    /**
     * 是否允许全屏
     */
    private var mAllowFullScreen = false
    /**
     * 是否沉浸状态栏
     */
    private var isSetStatusBar = false
    /**
     * 是否禁止旋转屏幕
     */
    private var isAllowScreenRoate = true

    override fun onCreate(savedInstanceState: Bundle?) {

        //设置是否全屏
        if (mAllowFullScreen) {
            this.window.setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN)
            requestWindowFeature(Window.FEATURE_NO_TITLE)
        }
        super.onCreate(savedInstanceState)
        beforeInit()
        setContentView(layoutResID())
        initToolbar()
        initView()
        initData()
        ////初始化全局RX订阅者
        compositeSubscription = CompositeSubscription()
        RxBus.get().register(this)
        if (savedInstanceState != null) {
            initParam(savedInstanceState)
        } else if (intent != null && intent.extras != null) {
            initParam(intent.extras)
        }

        //设置是否沉浸式状态栏
        if (isSetStatusBar) {
            steepStatusBar()
        }
        //设置是否禁止旋转屏幕
        if (isAllowScreenRoate) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        } else {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }
        //一些业务操作
        doBusiness(this)
    }

    /**
     * 界面初始化前期准备
     */
    protected open fun beforeInit() {

    }

    open fun show2Loading() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog(this)
        }
        if (!loadingDialog!!.isShowing()) {
            loadingDialog!!.show()
        }
    }

    open fun hide2Loading() {
        if (loadingDialog != null && loadingDialog!!.isShowing()) {
            loadingDialog!!.dismiss()
        }
    }

    /**
     * 设置沉浸式状态栏
     */
    private fun steepStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            window.addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            // 透明导航栏
            window.addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        }
    }

    /**
     * 设置是否全屏
     *
     * @param allowFullScreen
     */
    fun setAllowFullScreen(allowFullScreen: Boolean) {
        this.mAllowFullScreen = allowFullScreen
    }

    /**
     * 是否设置沉浸状态栏
     *
     * @param isSetStatusBar
     */
    fun setSteepStatusBar(isSetStatusBar: Boolean) {
        this.isSetStatusBar = isSetStatusBar
    }

    /**
     * 设置是否禁止旋转屏幕
     *
     * @param isAllowScreenRoate
     */
    fun setScreenRoate(isAllowScreenRoate: Boolean) {
        this.isAllowScreenRoate = isAllowScreenRoate
    }

    /**
     * 初始化toolbar
     */
    abstract fun initToolbar()


    /**
     * 初始化View
     */
    abstract fun initView()

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * [业务操作]
     *
     * @param mContext
     */
    abstract fun doBusiness(mContext: Context)

    /**
     * 资源文件
     *
     * @return
     */
    abstract fun layoutResID(): Int

    /**
     * 页面间传参数的
     *
     * @param bundle
     */
    protected fun initParam(bundle: Bundle?) {

    }

    fun toast(text: String) {
        ToastUtils.showShort(text)
    }

    /**
     * 日志输出
     *
     * @param msg
     */
    fun TLog(msg: String) {
        if (AppUtils.isAppDebug()) {
            LogUtils.d(msg)
        }
    }

    /**
     * 隐藏软件盘
     */
    fun hideSoftInput() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (currentFocus != null) {
            imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        }
    }

    /**
     * 点击软键盘之外的空白处，隐藏软件盘
     *
     * @param ev
     * @return
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                if (hideInputMethod(this, v)) {
                    return true //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 显示软键盘
     */
    fun showInputMethod() {
        if (currentFocus != null) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInputFromInputMethod(currentFocus!!.windowToken, 0)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (compositeSubscription != null && !compositeSubscription!!.isUnsubscribed) {
            compositeSubscription!!.unsubscribe()
        }
        if (loadingDialog != null) {
            loadingDialog = null
        }
        RxBus.get().unregister(this)
    }

    companion object {

        fun hideInputMethod(context: Context, v: View): Boolean {
            val imm = context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            return imm?.hideSoftInputFromWindow(v.windowToken, 0) ?: false
        }

        fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
            if (v != null && v is EditText) {
                val leftTop = intArrayOf(0, 0)
                v.getLocationInWindow(leftTop)
                val left = leftTop[0]
                val top = leftTop[1]
                val bottom = top + v.height
                val right = left + v.width
                return if (event.x > left && event.x < right
                        && event.y > top && event.y < bottom) {
                    // 保留点击EditText的事件
                    false
                } else {
                    true
                }
            }
            return false
        }
    }
}
